/*******************************************************************************
 * Copyright (c) 2025 Lablicate GmbH.
 *
 * This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License 2.0
 * which is available at https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 * 
 * Contributors:
 * Philip Wenig - initial API and implementation
 *******************************************************************************/
package org.eclipse.chemclipse.tsd.model.validators;

import org.eclipse.chemclipse.model.core.IChromatogramOverview;
import org.eclipse.chemclipse.support.util.ValueParserSupport;
import org.eclipse.chemclipse.tsd.model.core.TraceRange1D;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;

public class TraceRangeValidator1D extends ValueParserSupport implements IValidator<Object> {

	private int retentionTimeColumn1Start = 0;
	private int retentionTimeColumn1Stop = 0;
	private String name = "";
	private String traces = "";

	@Override
	public IStatus validate(Object value) {

		String message = null;
		if(value == null) {
			message = "Value can't be null";
		} else {
			if(value instanceof String content) {
				String text = content.trim();
				if(text.isEmpty()) {
					message = "Entry can't be empty";
				} else {
					/*
					 * Extract the values
					 */
					retentionTimeColumn1Start = 0;
					retentionTimeColumn1Stop = 0;
					name = "";
					traces = "";

					String[] values = text.trim().split("\\" + '|'); // The pipe needs to be escaped.
					if(values.length > 1) {
						/*
						 * Evaluation
						 */
						retentionTimeColumn1Start = (int)(parseDouble(values, 0) * IChromatogramOverview.MINUTE_CORRELATION_FACTOR);
						if(retentionTimeColumn1Start < 0.0d) {
							message = "The retention time start (Column1) must not be < 0.";
						}

						retentionTimeColumn1Stop = (int)(parseDouble(values, 1) * IChromatogramOverview.MINUTE_CORRELATION_FACTOR);
						if(retentionTimeColumn1Stop < 0.0d) {
							message = "The retention time stop (Column1) must not be < 0.";
						}

						name = parseString(values, 2);
						traces = parseString(values, 3);
					} else {
						message = "Please enter a valid trace range.";
					}
				}
			} else {
				message = "Value has to be a string.";
			}
		}

		if(message != null) {
			return ValidationStatus.error(message);
		} else {
			return ValidationStatus.ok();
		}
	}

	public TraceRange1D getSetting() {

		TraceRange1D traceRange = new TraceRange1D();
		traceRange.setRetentionTimeColumn1Start(retentionTimeColumn1Start);
		traceRange.setRetentionTimeColumn1Stop(retentionTimeColumn1Stop);
		traceRange.setName(name);
		traceRange.setTraces(traces);

		return traceRange;
	}
}